package cn.op.portal.utils;

import java.awt.Dimension;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;


/**
 * @author lufei
 *	图片缩略图工具
 */
public class ImgThumUtil {
	/**
	 * @param imgsrc 源文件，支持jpg，gif.....
	 * @param imgdist 目标缩略图文件,文件不存在会自动创建
	 * @param widthdist 缩略图宽度
	 * @param heightdist 缩略图高度
	 */
	public static void reduceImg(String imgsrc, String imgdist, int widthdist,
			int heightdist) {
		try {
			File srcfile = new File(imgsrc);
			if (!srcfile.exists()) {
				return;
			}
			Image image = javax.imageio.ImageIO.read(srcfile);
			
			//计算同比缩放大小，试验发现如果目标缩略图大小是正方形，而原始图片是长方形，同比后生成的图也是长方形，在正方形框中显示的效果就不太好；还没有不同比的好
//			Dimension d = new Dimension(image.getWidth(null), image.getHeight(null)).getSize();			
//	        int w = (int)d.getWidth();  
//	        int h = (int)d.getHeight();  
//	        if (w <= widthdist && h <= heightdist) {  
//	           //如果图片较小，则保持原来大小
//	        } else {  
//	            //同比缩放  
//	            if (w > widthdist || h > heightdist) {  
//	                if(w * heightdist > h * widthdist){  
//	                    heightdist = h * widthdist / w;  
//	                }else{  
//	                    widthdist = w * heightdist / h;  
//	                }  
//	            } else {  
//	                widthdist = w;  
//	                heightdist = h;  
//	            }  
//	        }  
	       
	        
			BufferedImage tag= new BufferedImage((int) widthdist, (int) heightdist,
					BufferedImage.TYPE_INT_RGB);
			
			tag.getGraphics().drawImage(image.getScaledInstance(widthdist, heightdist,  Image.SCALE_SMOOTH), 0, 0,  null);
//			tag.getGraphics().drawImage(src.getScaledInstance(widthdist, heightdist,  Image.SCALE_AREA_AVERAGING), 0, 0,  null);
			
			FileOutputStream out = new FileOutputStream(imgdist);
			JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
			encoder.encode(tag);
			out.close();

		} catch (IOException ex) {
			ex.printStackTrace();
		}
	}
	public static void main(String[] args) {
		String imgsrc = "D:/temp/webapps/Towel/images/amXcXxeagMMfeMgsBa9iUw==.JPG";
		String imgdist = "D:/temp/webapps/Towel/images/amXcXxeagMMfeMgsBa9iUw==_thum.JPG";
		reduceImg(imgsrc, imgdist, 90, 90);
		
//		File forder = new File("D:/temp/webapps/Towel/images/");
//		File[] files = forder.listFiles();
//		for (File file:files) {
//			if(file.isFile()){
//				imgsrc = file.getAbsolutePath();
//				String name = "thum_" + file.getName();
//				imgdist = file.getParentFile() + "/" + name;
////				System.out.println(imgdist);
//				reduceImg(imgsrc, imgdist, 90, 90);
//			}
//		}
		

		
	}
}
